import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Data, Status } from './type'
import type { SizeType } from 'antd/es/config-provider/SizeContext'
import { InputIds, OutputIds } from './constants'
import css from './runtime.less'
import { Tabs } from 'antd'

function EditRender({ env, data, inputs, outputs, slots }: any) {
  const [activeKey, setActiveKey] = useState(data.statusList?.[0]?.id || undefined)
  let active = activeKey
  if (data.statusList && data.statusList.length > 0) {
    if (!data.statusList.some((item: any) => item.id == active)) {
      active = data.statusList[0].id
    }
  }
  return (
    <div>
      <Tabs
        activeKey={active}
        type="card"
        size="small"
        onChange={setActiveKey}
        items={data.statusList.map((status: any, index: number) => {
          const id = status.id
          let title = status.title
          if (![undefined, null].includes(status.value)) {
            title += `(${status.value})`
          }
          return {
            label: (
              <>
                {title}
                <div style={{ pointerEvents: 'all', width: '100%', height: '100%', position: 'absolute', top: 0, left: 0 }}></div>
              </>
            ),
            key: id
          }
        })}
      />
      {slots?.[active]?.render?.()}
    </div>
  )
}
function RuntimeRender({ env, data, inputs, outputs, slots }: any) {
  const [value, setValue] = useState<string | undefined>(data.value)
  const id = data.statusList?.find?.((item) => item.value == value)?.id
  inputs[InputIds.SetValue]((val, relOutput) => {
    setValue(val)
    relOutput[OutputIds.SetValueDone](val)
  })

  inputs[InputIds.GetValue]((val, relOutput) => {
    relOutput[OutputIds.ReturnValue](value)
  })
  return id ? slots[id]?.render?.() : null
}

export default function (props: any) {
  return props.env.edit ? <EditRender {...props} /> : <RuntimeRender {...props} />
}
